package com.sk.cardeal.act.home.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.R;
import com.sk.cardeal.adapter.CostListAdater;
import com.sk.cardeal.adapter.FixPartsAdapter;
import com.sk.cardeal.adapter.FixProjectAdapter;
import com.sk.cardeal.adapter.FormProjectAdapter;
import com.sk.cardeal.adapter.NewFixByAdapter;
import com.sk.cardeal.app.MyApplication;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.callback.PriceChangedCallback;
import com.sk.cardeal.common.Constants;
import com.sk.cardeal.entity.ApplyFormEntity;
import com.sk.cardeal.entity.Brand;
import com.sk.cardeal.entity.BrandListBean;
import com.sk.cardeal.entity.ByKindList;
import com.sk.cardeal.entity.CostType;
import com.sk.cardeal.entity.CustomDetails;
import com.sk.cardeal.entity.FixType;
import com.sk.cardeal.entity.FixTypeList;
import com.sk.cardeal.entity.Model;
import com.sk.cardeal.entity.NewPartsList;
import com.sk.cardeal.entity.OcrInfo;
import com.sk.cardeal.entity.PartsListBean;
import com.sk.cardeal.entity.Project;
import com.sk.cardeal.entity.ProjectListBean;
import com.sk.cardeal.entity.RepairOrderDetail;
import com.sk.cardeal.entity.WorkFormDetails;
import com.sk.cardeal.entity.WorkPostion;
import com.sk.cardeal.entity.WorkPostionList;
import com.sk.cardeal.entity.Worker;
import com.sk.cardeal.entity.WorkerListBean;
import com.sk.cardeal.entity.XingShiEntity;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.FileUtil;
import com.sk.cardeal.utils.HttpAddress;
import com.sk.cardeal.utils.MyApplicationLike;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.RecognizeService;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.view.IconViewTextView;
import com.sk.cardeal.view.LineMenuView;
import com.sk.cardeal.view.TitleView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.sk.cardeal.common.Constants.CAR_CARD;
import static com.sk.cardeal.common.Constants.CHOOSE_BY_PARTS;
import static com.sk.cardeal.common.Constants.CHOOSE_CAR_TYPE;
import static com.sk.cardeal.common.Constants.CHOOSE_FIX_PEP;
import static com.sk.cardeal.common.Constants.CHOOSE_PARTS;
import static com.sk.cardeal.common.Constants.CHOOSE_PROJECT;
import static com.sk.cardeal.common.Constants.CHOOSE_TYPE;
import static com.sk.cardeal.common.Constants.CHOOSE_WORK_POSTION;
import static com.sk.cardeal.common.Constants.OTHER_PAY;
import static com.sk.cardeal.common.Constants.UPLOAD_JIASHI;
import static com.sk.cardeal.common.Constants.UPLOAD_XINGSHI;

/**
 * Created by sk on 2017/12/15.
 */

public class FixActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, HandleDataCallBack, PriceChangedCallback {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.scan)
    ImageView scan;
    @BindView(R.id.car_num)
    EditText carNum;
    @BindView(R.id.car_type)
    LineMenuView carType;
    @BindView(R.id.fix_type)
    LineMenuView fixType;
    @BindView(R.id.scan_frame)
    ImageView scanFrame;
    @BindView(R.id.frame_num)
    EditText frameNum;
    @BindView(R.id.fix_pep)
    LineMenuView fixPep;
    @BindView(R.id.in_date)
    LineMenuView inDate;
    @BindView(R.id.danwei)
    TextView danwei;
    @BindView(R.id.car_owner)
    EditText carOwner;
    @BindView(R.id.send_pep)
    EditText sendPep;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.ed_card_num)
    EditText edCardNum;
    @BindView(R.id.ed_advice)
    EditText edAdvice;
    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.close_ll)
    FrameLayout closeLl;
    @BindView(R.id.detail_ll)
    LinearLayout detailLl;
    @BindView(R.id.card_head)
    ImageView cardHead;
    @BindView(R.id.tv_car_num)
    TextView tvCarNum;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.s_fix_type)
    LineMenuView sFixType;
    @BindView(R.id.open)
    ImageView open;
    @BindView(R.id.open_ll)
    FrameLayout openLl;
    @BindView(R.id.simple_ll)
    LinearLayout simpleLl;
    @BindView(R.id.project)
    IconViewTextView project;
    @BindView(R.id.parts)
    IconViewTextView parts;
    @BindView(R.id.other_pay)
    IconViewTextView otherPay;
    @BindView(R.id.save)
    TextView save;
    @BindView(R.id.apply_form)
    TextView applyForm;
    @BindView(R.id.is_send)
    CheckBox isSend;
    @BindView(R.id.project_ryc)
    RecyclerView projectRyc;
    @BindView(R.id.parts_ryc)
    RecyclerView partsRyc;
    @BindView(R.id.other_ryc)
    RecyclerView otherRyc;
    @BindView(R.id.finish_date)
    LineMenuView finishDate;
    @BindView(R.id.ed_in_km)
    EditText edInKm;
    @BindView(R.id.parts_by)
    IconViewTextView partsBy;
    @BindView(R.id.parts_by_ryc)
    RecyclerView partsByRyc;

    private LoadingDialog loadingDialog;


    private String typeId = "";

    private ArrayList<ByKindList.ResultListBean> allByPartsList = new ArrayList<>();

    private ArrayList<ByKindList.ResultListBean> selectByPartsList = new ArrayList<>();

    private ArrayList<NewPartsList.ResultListBean.PartsQualityListBean> newSelectPartsList = new ArrayList<>();

    private ArrayList<Project> selectProjectList = new ArrayList<>();

    private FixPartsAdapter fixPartsAdapter;

    private NewFixByAdapter fixByPartsAdapter;

    private FixProjectAdapter fixProjectAdapter;

    private CostListAdater costListAdater;

    private List<CostType> costTypeList = new ArrayList<>();

    private List<RepairOrderDetail> repairOrderDetails = new ArrayList<>();

    private FixType selectType;

    private ApplyFormEntity applyFormEntity;


    private int isFrom = 0;

    private int isUpdate = 0;

    private String orderId = "";

    private String brandUrl = "";

    private String carCode = "";


    @Override
    protected int getContentView() {
        return R.layout.activity_fix;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleView.setMyCallBack(this);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);

        isUpdate = getIntent().getIntExtra("isUpdate", 0);

        applyFormEntity = new ApplyFormEntity();

        if (isUpdate == 1) {
            orderId = getIntent().getStringExtra("orderId");
            applyFormEntity.setId(orderId);
            loadingDialog.show();
            AppApi.workFormDetails(orderId, this, 200, this);
        } else {
            applyFormEntity.setCode(MyUtils.getRndNumCode());
        }

        applyFormEntity.setUserId(MyUtils.getUser(mContext).getId());
        applyFormEntity.setCompanyId(MyUtils.getUser(mContext).getCompanyId());
        applyFormEntity.setIsUpdate(isUpdate);
        applyFormEntity.setType(0);
        applyFormEntity.setIsSend(0);
        titleView.setMyCallBack(this);
        intRyc();
        isSend.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    applyFormEntity.setIsSend(0);
                } else {
                    applyFormEntity.setIsSend(2);
                }
            }
        });

        carNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvCarNum.setText(s.toString());
                if (s.length() == 7) {
                    if (MyUtils.isCarNumber(s.toString())) {

                        AppApi.customDetails(s.toString(), FixActivity.this, 300, FixActivity.this);

                    } else {
                        SnackUtils.showError(mRootView, "您输入的车牌号，不合法！");
                    }
                }
            }
        });

        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvPhone.setText(s.toString());
            }
        });
    }


    private void intRyc() {
        partsRyc.setLayoutManager(new LinearLayoutManager(mContext));
        fixPartsAdapter = new FixPartsAdapter(R.layout.item_fix_parts, newSelectPartsList,this);
        partsRyc.setAdapter(fixPartsAdapter);
        fixPartsAdapter.setOnItemClickListener(this);
        fixPartsAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.finish_edit:
                        TextView textView = (TextView) adapter.getViewByPosition(partsRyc, position, R.id.edit_num);
                        int count = Integer.parseInt(textView.getText().toString());
                        if (count != 0) {
                            newSelectPartsList.get(position).setWantCount(count);
                            newSelectPartsList.get(position).setOpen(false);
                            adapter.notifyItemChanged(position);
                        } else {
                            newSelectPartsList.remove(position);
                            adapter.notifyDataSetChanged();
                        }

                        break;
                    case R.id.edit_btn:
                        newSelectPartsList.get(position).setOpen(true);
                        adapter.notifyItemChanged(position);
                        break;
                }
            }
        });

        partsByRyc.setLayoutManager(new LinearLayoutManager(mContext));
        fixByPartsAdapter = new NewFixByAdapter(R.layout.item_new_fix_by_parts, selectByPartsList);
        partsByRyc.setAdapter(fixByPartsAdapter);
        fixByPartsAdapter.setOnItemClickListener(this);
        fixByPartsAdapter.setOnItemChildClickListener(this);

        projectRyc.setLayoutManager(new LinearLayoutManager(mContext));
        fixProjectAdapter = new FixProjectAdapter(R.layout.item_quickly_fix_project, selectProjectList);
        projectRyc.setAdapter(fixProjectAdapter);
        fixProjectAdapter.setOnItemClickListener(this);
        fixProjectAdapter.setOnItemChildClickListener(this);

        otherRyc.setLayoutManager(new LinearLayoutManager(mContext));
        costListAdater = new CostListAdater(R.layout.item_cost, costTypeList);
        otherRyc.setAdapter(costListAdater);
        costListAdater.setOnItemClickListener(this);
        costListAdater.setOnItemChildClickListener(this);


        partsRyc.setHasFixedSize(true);
        partsRyc.setNestedScrollingEnabled(false);

        partsByRyc.setHasFixedSize(true);
        partsByRyc.setNestedScrollingEnabled(false);

        projectRyc.setHasFixedSize(true);
        projectRyc.setNestedScrollingEnabled(false);

        otherRyc.setHasFixedSize(true);
        otherRyc.setNestedScrollingEnabled(false);
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i) {
            case 1:
                finish();
                break;
        }
    }


    @OnClick({R.id.parts_by, R.id.scan, R.id.scan_frame, R.id.close_ll, R.id.open_ll, R.id.project, R.id.parts, R.id.other_pay, R.id.car_type, R.id.fix_pep, R.id.in_date, R.id.finish_date, R.id.fix_type, R.id.apply_form, R.id.save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.parts_by:
                if (carCode.length() == 0) {
                    SnackUtils.showError(mRootView, "请选择车型");
                    return;
                }
                if (TextUtils.isEmpty(edInKm.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入进场里程");
                    return;
                }
                loadingDialog.show();
                AppApi.getByPartsByKm(carCode, edInKm.getText().toString(), FixActivity.this, 400, FixActivity.this);
                break;

            case R.id.scan:
                if (MyApplicationLike.isHasGotToken()) {
                    Intent scanIntent = new Intent(mContext, CameraActivity.class);
                    scanIntent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                            FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                    scanIntent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                            CameraActivity.CONTENT_TYPE_BANK_CARD);
                    startActivityForResult(scanIntent, CAR_CARD);
                } else {
                    SnackUtils.showError(mRootView, "ocr扫描尚未准备就绪！");
                }
                break;

            case R.id.scan_frame:

                if (MyApplicationLike.isHasGotToken()) {
                    Intent scanIntent = new Intent(mContext, CameraActivity.class);
                    scanIntent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                            FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                    scanIntent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                            CameraActivity.CONTENT_TYPE_BANK_CARD);
                    startActivityForResult(scanIntent, UPLOAD_JIASHI);
                } else {
                    SnackUtils.showError(mRootView, "ocr扫描尚未准备就绪！");
                }


                break;

            case R.id.close_ll:
                detailLl.setVisibility(View.GONE);
                simpleLl.setVisibility(View.VISIBLE);
                break;

            case R.id.open_ll:
                detailLl.setVisibility(View.VISIBLE);
                simpleLl.setVisibility(View.GONE);
                break;

            case R.id.project:
                loadingDialog.show();
                AppApi.getFixProject(0, FixActivity.this, 6, FixActivity.this);
                break;
            case R.id.parts:
                if (typeId != null && typeId.length() > 0) {
                    Intent intent = new Intent(mContext, NewChoosePartsActivity.class);
                    intent.putExtra("id", typeId);
                    intent.putExtra("vin", frameNum.getText().toString());
                    intent.putExtra("data", newSelectPartsList);
                    startActivityForResult(intent, Constants.CHOOSE_PARTS);
                } else {
                    Toast.makeText(mContext, "请先选择车型！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.other_pay:
                Intent costIntent = new Intent(mContext, NewCostActivity.class);
                startActivityForResult(costIntent, OTHER_PAY);
                break;

            case R.id.car_type:
                loadingDialog.show();
                AppApi.getCarBrand(FixActivity.this, 1, FixActivity.this);
                break;
            case R.id.fix_pep:
                loadingDialog.show();
                AppApi.getCompanyWorker(FixActivity.this, 2, FixActivity.this);
                break;
            case R.id.in_date:
                DatePickDialog dialog = new DatePickDialog(this);
                //设置上下年分限制
                dialog.setYearLimt(5);
                //设置标题
                dialog.setTitle("选择进场日期");
                //设置类型
                dialog.setType(DateType.TYPE_ALL);
                //设置消息体的显示格式，日期格式
                dialog.setMessageFormat("yyyy-MM-dd HH:mm");
                //设置选择回调
                dialog.setOnChangeLisener(null);
                //设置点击确定按钮回调
                dialog.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        inDate.setHint(MyUtils.stampToDate(date.getTime()));
                        applyFormEntity.setInTime(MyUtils.stampToDate(date.getTime()));
                        inDate.setHintColor(Color.parseColor("#232323"));
                    }
                });
                dialog.show();
                break;
            case R.id.finish_date:

                DatePickDialog dialog1 = new DatePickDialog(this);
                //设置上下年分限制
                dialog1.setYearLimt(5);
                //设置标题
                dialog1.setTitle("选择预计完工日期");
                //设置类型
                dialog1.setType(DateType.TYPE_ALL);
                //设置消息体的显示格式，日期格式
                dialog1.setMessageFormat("yyyy-MM-dd HH:mm");
                //设置选择回调
                dialog1.setOnChangeLisener(null);
                //设置点击确定按钮回调
                dialog1.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        finishDate.setHint(MyUtils.stampToDate(date.getTime()));
                        applyFormEntity.setAboutOverTime(MyUtils.stampToDate(date.getTime()));
                        finishDate.setHintColor(Color.parseColor("#232323"));
                    }
                });
                dialog1.show();
                break;

            case R.id.fix_type:
                loadingDialog.show();
                AppApi.getFixType(FixActivity.this, 7, FixActivity.this);
                break;
            case R.id.save:


                if (TextUtils.isEmpty(carNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入您的车牌号！");
                    return;
                }

                if (!MyUtils.isCarNumber(carNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "您输入的车牌号不合法！");
                    return;
                }

                if (TextUtils.isEmpty(frameNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入您的车架号！");
                    return;
                }

                if (TextUtils.isEmpty(phone.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入联系电话！");
                    return;
                }

                setData();
                loadingDialog.show();
                AppApi.saveForm(applyFormEntity, FixActivity.this, 100, FixActivity.this);
                break;
            case R.id.apply_form:

                if (TextUtils.isEmpty(carNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入您的车牌号！");
                    return;
                }

                if (!MyUtils.isCarNumber(carNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "您输入的车牌号不合法！");
                    return;
                }

                if (TextUtils.isEmpty(frameNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入您的车架号！");
                    return;
                }

                if (TextUtils.isEmpty(phone.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入联系电话！");
                    return;
                }

                setData();
                loadingDialog.show();
                AppApi.submitForm(applyFormEntity, FixActivity.this, 101, FixActivity.this);
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        if (adapter instanceof FormProjectAdapter) {
            switch (view.getId()) {
                case R.id.right:
                    selectProjectList.remove(position);
                    fixProjectAdapter.notifyDataSetChanged();
                    break;

                case R.id.finish_edit:
                    selectProjectList.get(position).setOpen(false);
                    EditText editText = (EditText) adapter.getViewByPosition(projectRyc, position, R.id.price);
                    selectProjectList.get(position).setEditPrice(Double.parseDouble(editText.getText().toString()));
                    fixProjectAdapter.notifyItemChanged(position);
                    break;

                case R.id.edit_btn:
                    selectProjectList.get(position).setOpen(true);
                    adapter.notifyItemChanged(position);
                    break;

            }
        } else if (adapter instanceof CostListAdater) {
            switch (view.getId()) {
                case R.id.right:
                    costTypeList.remove(position);
                    costListAdater.notifyDataSetChanged();
                    break;
            }
        }else if (adapter instanceof NewFixByAdapter) {
            switch (view.getId()) {
                case R.id.right:
                    ByKindList.ResultListBean dataBean = selectByPartsList.get(position);
                    for (ByKindList.ResultListBean data : allByPartsList) {
                        if (data.getId().equals(dataBean.getId())) {
                            data.setChoose(false);
                        }
                    }
                    selectByPartsList.remove(position);
                    fixByPartsAdapter.notifyDataSetChanged();
                    break;
            }
        }

    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 1:
                BrandListBean brandListBean = JSON.parseObject(result, BrandListBean.class);
                ArrayList<Brand> brandList = (ArrayList<Brand>) brandListBean.getResultList();
                Intent carIntent = new Intent(mContext, BrandChooseActivity.class);
                carIntent.putParcelableArrayListExtra("data", brandList);
                startActivityForResult(carIntent, CHOOSE_CAR_TYPE);
                break;
            case 2:
                WorkerListBean workerListBean = JSON.parseObject(result, WorkerListBean.class);
                ArrayList<Worker> workerArrayList = (ArrayList<Worker>) workerListBean.getResultList();
                Intent workIntent = new Intent(mContext, PepChooseActivity.class);
                workIntent.putParcelableArrayListExtra("data", workerArrayList);
                startActivityForResult(workIntent, CHOOSE_FIX_PEP);
                break;
            case 3:
                PartsListBean partsListBean = JSON.parseObject(result, PartsListBean.class);
                ArrayList<PartsListBean.ResultListBean> partsList = (ArrayList<PartsListBean.ResultListBean>) partsListBean.getResultList();
                Intent partsIntent = new Intent(mContext, ChoosePartsActivity.class);
                partsIntent.putExtra("data", partsList);
                partsIntent.putExtra("type", typeId);
                partsIntent.putExtra("select", newSelectPartsList);
                startActivityForResult(partsIntent, CHOOSE_PARTS);
                break;
            case 6:
                ProjectListBean projectListBean = JSON.parseObject(result, ProjectListBean.class);
                ArrayList<Project> projectArrayList = (ArrayList<Project>) projectListBean.getResultList();
                Intent projectIntent = new Intent(mContext, ChooseFixProjectActivity.class);
                projectIntent.putParcelableArrayListExtra("data", projectArrayList);
                projectIntent.putParcelableArrayListExtra("select", selectProjectList);
                projectIntent.putExtra("type", 0);
                startActivityForResult(projectIntent, CHOOSE_PROJECT);
                break;
            case 7:
                FixTypeList fixTypeList = JSON.parseObject(result, FixTypeList.class);
                ArrayList<FixType> fixTypes = (ArrayList<FixType>) fixTypeList.getResultList();
                Intent intent = new Intent(mContext, FixTypeActivity.class);
                intent.putExtra("data", fixTypes);
                startActivityForResult(intent, CHOOSE_TYPE);
                break;
            case 8:
                WorkPostionList workPostionList = JSON.parseObject(result, WorkPostionList.class);
                ArrayList<WorkPostion> workFormList = (ArrayList<WorkPostion>) workPostionList.getResultList();
                Intent posintent = new Intent(mContext, ChooseWorkPostionActivity.class);
                posintent.putParcelableArrayListExtra("data", workFormList);
                startActivityForResult(posintent, CHOOSE_WORK_POSTION);
                break;
            case 100:
                Toast.makeText(mContext, "工单保存成功！", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finish();
                break;
            case 101:
                Toast.makeText(mContext, "工单提交成功！", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finish();
                break;

            case 200:

                //保存订单后进入

                WorkFormDetails workFormDetails = JSON.parseObject(result, WorkFormDetails.class);

                //车型
                carType.setHint(workFormDetails.getReturnObject().getCarName());
                carType.setHintColor(Color.parseColor("#232323"));
                typeId = workFormDetails.getReturnObject().getCarTypeId();
                applyFormEntity.setCarTypeId(typeId);

                frameNum.setText(workFormDetails.getReturnObject().getCarVin());
                carNum.setText(workFormDetails.getReturnObject().getCarNumber());
                sendPep.setText(workFormDetails.getReturnObject().getSendRepairUserName());
                carOwner.setText(workFormDetails.getReturnObject().getCustomName());

                fixType.setHint(workFormDetails.getReturnObject().getRepairName());
                fixType.setHintColor(Color.parseColor("#232323"));
                applyFormEntity.setRepairType(workFormDetails.getReturnObject().getRepairType());

                //主修人
                fixPep.setHint(workFormDetails.getReturnObject().getMainName());
                fixPep.setHintColor(Color.parseColor("#232323"));
                applyFormEntity.setMainRepairUserId(workFormDetails.getReturnObject().getMainRepairUserId());

                //进场日期
                inDate.setHint(workFormDetails.getReturnObject().getInTime());
                applyFormEntity.setInTime(workFormDetails.getReturnObject().getInTime());
                inDate.setHintColor(Color.parseColor("#232323"));

                //预计完成日期
                finishDate.setHint(workFormDetails.getReturnObject().getAboutOverTime());
                applyFormEntity.setAboutOverTime(workFormDetails.getReturnObject().getAboutOverTime());
                finishDate.setHintColor(Color.parseColor("#232323"));

                edInKm.setText(workFormDetails.getReturnObject().getMileage());
                edAdvice.setText(workFormDetails.getReturnObject().getRepairTips());
                phone.setText(workFormDetails.getReturnObject().getPhone());
                edCardNum.setText(workFormDetails.getReturnObject().getVipNumber());


                applyFormEntity.setCode(workFormDetails.getReturnObject().getCode());
                List<WorkFormDetails.ReturnObjectBean.RepairOrderDetailListBean> dataBeanList = workFormDetails.getReturnObject().getRepairOrderDetailList();
                for (WorkFormDetails.ReturnObjectBean.RepairOrderDetailListBean detailListBean : dataBeanList) {
                    switch (detailListBean.getType()) {
                        case 1:
                            Project project = new Project();
                            project.setSelect(true);
                            project.setId(detailListBean.getRepairProId());
                            project.setEditPrice(detailListBean.getOtherPrice());
                            project.setProjectName(detailListBean.getProject_name());
                            selectProjectList.add(project);
                            break;
                        case 2:
                            NewPartsList.ResultListBean.PartsQualityListBean parts = new NewPartsList.ResultListBean.PartsQualityListBean();
                            parts.setWantCount(detailListBean.getNum());
                            parts.setEditPrice(detailListBean.getOtherPrice());
                            parts.setCarWarehousePartsId(detailListBean.getPartId());
                            parts.setPartsName(detailListBean.getPartName());
                            newSelectPartsList.add(parts);
                            break;
                        case 3:
                            CostType costType = new CostType();
                            costType.setRemark(detailListBean.getOtherRemark());
                            costType.setCostName(detailListBean.getOtherName());
                            costType.setCost(String.valueOf(detailListBean.getOtherCost()));
                            costType.setPrice(String.valueOf(detailListBean.getOtherPrice()));
                            costTypeList.add(costType);
                            break;
                    }
                }
                fixProjectAdapter.notifyDataSetChanged();
                fixPartsAdapter.notifyDataSetChanged();
                costListAdater.notifyDataSetChanged();
                break;

            case 300:

                CustomDetails customDetails = JSON.parseObject(result, CustomDetails.class);
                if (TextUtils.isEmpty(carOwner.getText().toString())) {
                    carOwner.setText(customDetails.getReturnObject().getPersonName());
                }
                if (TextUtils.isEmpty(phone.getText().toString())) {
                    phone.setText(customDetails.getReturnObject().getTelephone());
                }
                if (TextUtils.isEmpty(frameNum.getText().toString())) {
                    frameNum.setText(customDetails.getReturnObject().getBaseCustomerCar().getEngineNo());
                }

                typeId = customDetails.getReturnObject().getBaseCustomerCar().getCarTypeId();
                if (TextUtils.isEmpty(carType.getHint()) && !TextUtils.isEmpty(customDetails.getReturnObject().getBaseCustomerCar().getBrandModelName())) {
                    carType.setHint(customDetails.getReturnObject().getBaseCustomerCar().getBrandModelName());
                    carType.setHintColor(Color.parseColor("#232323"));
                }

                break;
            case 400:
                Intent byIntent = new Intent(mContext, NewChooseByPartsActivity.class);
                byIntent.putExtra("data", result);
                byIntent.putExtra("carCode", carCode);
                byIntent.putExtra("km", edInKm.getText().toString());
                byIntent.putParcelableArrayListExtra("list", allByPartsList);
                startActivityForResult(byIntent, Constants.CHOOSE_BY_PARTS);
                break;
        }
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();

    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case CHOOSE_CAR_TYPE:
                    Model model = data.getParcelableExtra("model");
                    brandUrl = data.getStringExtra("url");
                    Glide.with(mContext).load(HttpAddress.ossPath + brandUrl).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(cardHead);
                    carType.setHint(model.getText());
                    carType.setHintColor(Color.parseColor("#232323"));
                    typeId = model.getId();
                    carCode = model.getCode();
                    applyFormEntity.setCarTypeId(typeId);
                    break;
                case CHOOSE_FIX_PEP:
                    Worker worker = data.getParcelableExtra("worker");
                    fixPep.setHint(worker.getPersonName());
                    fixPep.setHintColor(Color.parseColor("#232323"));
                    applyFormEntity.setMainRepairUserId(worker.getId());
                    break;
                case CHOOSE_PARTS:
                    newSelectPartsList.clear();
                    List<NewPartsList.ResultListBean.PartsQualityListBean> dataList = data.getParcelableArrayListExtra("data");
                    newSelectPartsList.addAll(dataList);
                    for (NewPartsList.ResultListBean.PartsQualityListBean parts : newSelectPartsList) {
                        parts.setEditPrice(parts.getPrice());
                    }
                    fixPartsAdapter.notifyDataSetChanged();
                    break;
                case CHOOSE_BY_PARTS:
                    allByPartsList.clear();
                    selectByPartsList.clear();
                    List<ByKindList.ResultListBean> byDataList = data.getParcelableArrayListExtra("data");
                    allByPartsList.addAll(byDataList);
                    for (ByKindList.ResultListBean entity : allByPartsList) {
                        if (entity.isChoose()) {
                            selectByPartsList.add(entity);
                        }
                    }
                    Log.v("selectByPartsList", JSON.toJSONString(selectByPartsList));
                    fixByPartsAdapter.notifyDataSetChanged();
                    break;
                case CHOOSE_PROJECT:
                    selectProjectList.clear();
                    List<Project> projects = data.getParcelableArrayListExtra("data");
                    selectProjectList.addAll(projects);
                    for (Project project : selectProjectList) {
                        if (project.getEditPrice() <= 0) {
                            project.setEditPrice(project.getAfterCutPrice());
                        }
                    }
                    fixProjectAdapter.notifyDataSetChanged();
                    break;
                case OTHER_PAY:
                    CostType costType = data.getParcelableExtra("data");
                    costTypeList.add(costType);
                    costListAdater.notifyDataSetChanged();
                    break;
                case CHOOSE_TYPE:
                    selectType = data.getParcelableExtra("data");
                    fixType.setHint(selectType.getName());
                    fixType.setHintColor(Color.parseColor("#232323"));
                    applyFormEntity.setRepairType(selectType.getId());
                    break;
                case CAR_CARD:
                    RecognizeService.recLicensePlate(FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(),
                            new RecognizeService.ServiceListener() {
                                @Override
                                public void onResult(String result, Bitmap bitmap) {
                                    Log.v("recLicensePlate", result);
                                    if (bitmap != null) {
                                        OcrInfo ocrInfo = JSONObject.parseObject(result, OcrInfo.class);
                                        carNum.setText(ocrInfo.getWords_result().getNumber());
                                    } else {
                                        SnackUtils.showError(mRootView, "识别失败，请重试!");
                                    }
                                }
                            });
                    break;

                case UPLOAD_XINGSHI:
                    RecognizeService.recVehicleLicense(FileUtil.getSaveFile(MyApplication.getAppContext()).getAbsolutePath(),
                            new RecognizeService.ServiceListener() {
                                @Override
                                public void onResult(String result, Bitmap bitmap) {
                                    Log.v("RecognizeService", result);
                                    if (bitmap != null) {
                                        XingShiEntity xingShiEntity = MyUtils.jsonToXingshi(result);
                                        if (xingShiEntity != null) {
                                            frameNum.setText(xingShiEntity.getEngineNumber());
                                        }
                                    } else {
                                        SnackUtils.showError(mRootView, "识别失败，请重试！");
                                    }
                                }
                            });
                    break;
            }
        }
    }

    private void setData() {
        applyFormEntity.setCarNumber(carNum.getText().toString());
        applyFormEntity.setCarVin(frameNum.getText().toString());
        applyFormEntity.setMileage(edInKm.getText().toString());
        applyFormEntity.setCustomName(carOwner.getText().toString());
        applyFormEntity.setSendRepairUserName(sendPep.getText().toString());
        applyFormEntity.setPhone(phone.getText().toString());
        applyFormEntity.setVipNumber(edCardNum.getText().toString());
        applyFormEntity.setRepairTips(edAdvice.getText().toString());

        for (Project project : selectProjectList) {

            RepairOrderDetail repairOrderDetail = new RepairOrderDetail();
            repairOrderDetail.setType(1);
            repairOrderDetail.setNum(1);
            repairOrderDetail.setRepairProId(project.getId());
            repairOrderDetail.setOtherPrice(project.getEditPrice());
            repairOrderDetails.add(repairOrderDetail);

        }

        for (NewPartsList.ResultListBean.PartsQualityListBean parts : newSelectPartsList) {

            RepairOrderDetail repairOrderDetail = new RepairOrderDetail();
            repairOrderDetail.setType(2);
            repairOrderDetail.setNum(parts.getWantCount());
            repairOrderDetail.setPartId(parts.getCarWarehousePartsId());
            repairOrderDetail.setOtherPrice(parts.getEditPrice());
            repairOrderDetails.add(repairOrderDetail);

        }

        for (CostType costType : costTypeList) {
            RepairOrderDetail repairOrderDetail = new RepairOrderDetail();
            repairOrderDetail.setType(3);
            repairOrderDetail.setNum(1);
            repairOrderDetail.setOtherName(costType.getCostName());
            repairOrderDetail.setOtherPrice(Double.parseDouble(costType.getPrice()));
            repairOrderDetail.setOtherCost(Double.parseDouble(costType.getCost()));
            repairOrderDetail.setOtherRemark(costType.getRemark());
            repairOrderDetails.add(repairOrderDetail);
        }
        applyFormEntity.setRepairOrderDetail(repairOrderDetails);
    }

    @Override
    public void priceChange(int pos, double price) {
        newSelectPartsList.get(pos).setEditPrice(price);
    }
}
